<?php

namespace App\Providers;


use App\Models\Admin\CustomerAdmin;
use App\Models\Admin\PanxAdmin;
use App\Models\Admin\StoreAdmin;
use App\Models\Customer\CustomerRelateHmSkin;
use App\Models\Customer\CustomerRelateWaxSkin;
use App\Models\Customer\DeviceAccount;
use App\Models\OpenWechat\WechatUser;
use App\Models\Panx\Product;
use App\Models\Store\CamSkinRecord;
use App\Models\Store\Pack;
use App\Models\Store\Store;
use App\Models\Url;
use App\Services\Utils\IpUtils;
use Illuminate\Database\Connection;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * @var int - MySql 查询计数，调试性能分析用
     */
    protected static $sql_count = 0;

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
//        Schema::defaultStringLength(191); // 数据迁移时默认设置长度
        Relation::morphMap([
            'PanxAdmin'     => PanxAdmin::class,
            'CustomerAdmin' => CustomerAdmin::class,
            'StoreAdmin'    => StoreAdmin::class,
            'CamSkinRecord' => CamSkinRecord::class,
            'Store'         => Store::class,
            'WechatUser'    => WechatUser::class,
            'DeviceAccount' => DeviceAccount::class,
            'Product'       => Product::class,
            'Pack'          => Pack::class,
            'Url'           => Url::class,
            'CustomerRelateHmSkin' => CustomerRelateHmSkin::class,
            'CustomerRelateWaxSkin' => CustomerRelateWaxSkin::class,
        ]);

        $this->logSqlQuery();

        $this->forwardForceHttps();
    }

    /**
     * 测试 log sql 查询语句到 laravel log 文件
     */
    private function logSqlQuery()
    {
        if (! config('app.dump_sql')) return;

        /**
         * @var DatabaseManager $conn
         */
        $conn = app('db');

        /**
         * @see Connection::logQuery()
         */
        $conn->listen(function (QueryExecuted $query) {
            logger($query->sql . ' | ' . $query->time . 'ms');
            logger($query->bindings);
            self::$sql_count++;
        });
    }

    public static function sqlCount(): int
    {
        return self::$sql_count;
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * 当上级代理有 X-Forwarded-Https 时，强制 UrlGenerator 方法生成 https
     * apache -> RequestHeader set X-Forwarded-Https "on"
     * nginx ?
     */
    private function forwardForceHttps()
    {
        if (request()->hasHeader('X-Forwarded-Https')) {
            \URL::forceScheme('https');
        }
    }
}
